package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

import static com.alibaba.com.caucho.hessian.io.HessianInputFactory.log;

@Controller
@RequestMapping("/user")
public class UserController {
	@Reference
	UserService userService;

	@RequestMapping("/loginSuccess")
	public String loginSuccess(){
		return "redirect:http://localhost:83/pages/main.html";
	}

	@RequestMapping("/loginFail")
	public String loginFail(){
		return "redirect:http://localhost:83/login.html";
	}

	@RequestMapping("/getUsername")
	@ResponseBody
	public Result getUsername(){
		//从授权框架上下文获取授权对象，再从授权对象获取授权框架用户对象User,最后获取用户名
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		if(principal instanceof User){
			User user = (User) principal;
			return new Result(true, MessageConst.GET_USERNAME_SUCCESS,user.getUsername());
		}
		return new Result(false, MessageConst.GET_USERNAME_FAIL);
	}
	@RequestMapping("/getUserMenu")
	@ResponseBody
	public Result getUserMenu(){
		//从授权框架上下文获取授权对象，再从授权对象获取授权框架用户对象User,最后获取用户名
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		if(principal instanceof User){
			User user = (User) principal;
           List<Map<String,Object>> menuList=userService.getUserMenu(user.getUsername());
			return new Result(true, "获取系统菜单成功",menuList);
		}
		return new Result(false, MessageConst.GET_USERNAME_FAIL);
	}
}